function databaseRandomSampling( databaseDir, nbDesiredImg, minWidth, minHeight, keepProportion )
%databaseRandomSampling takeAllImage in the dir and sample them randomly
%@databaseDir : where the data are
%@nbDesiredImg : number of image you want to have at the end. It should be
%higher than the # of files in databaseDir

savingSampleDir = [databaseDir 'sampled/'];
mkdir(savingSampleDir);

imgFiles = dir(databaseDir);
imgFileIndex = find(~[imgFiles.isdir]);
nbFiles = length(imgFileIndex);
nbOfSampling = ceil(nbDesiredImg/nbFiles);
nbOfImagesSaved = 0;

for i = 1:nbFiles
    imgFilename = imgFiles(imgFileIndex(i)).name;
    img = imread(cat(2,databaseDir,imgFilename));
    %if(size(img,3)>1)
    %    imgYCRCB = rgb2ycbcr(img);
    %    img = reshape(imgYCRCB(:,:,1),size(imgYCRCB,1),size(imgYCRCB,2));
    %end
    width = size(img,2);
    height = size(img,1);
    
    for j=1:nbOfSampling
        if(keepProportion)
            if(width>height)
                y = randi([1 height-minHeight],1,1);  
                sampleHeight = randi([minHeight height-y],1,1);
                sampleWidth = floor(minWidth*(sampleHeight/minHeight));
                x = randi([1 width-sampleWidth],1,1);
            else
                x = randi([1 width-minWidth],1,1);
                sampleWidth = randi([minWidth width-x],1,1);
                sampleHeight = floor(minHeight*(sampleWidth/minWidth));
                y = randi([1 height-sampleHeight],1,1);
            end
        else
            x = randi([1 width-minWidth],1,1);
            y = randi([1 height-minHeight],1,1);
            sampleWidth = randi([minWidth width-x],1,1);
            sampleHeight = randi([minHeight height-y],1,1);
        end
        sample = img(y:y+sampleHeight-1,x:x+sampleWidth-1,:);
        sampleFilename = [savingSampleDir imgFilename '_' num2str(j) '.png'];
        imwrite(sample,sampleFilename);
    end
    nbOfImagesSaved = nbOfImagesSaved + nbOfSampling;
end

fprintf('Number of images saved: %5i\n',nbOfImagesSaved);
end
